﻿using System.Collections.Immutable;

namespace DimensionsHelper.LanguageService.Syntax;

public abstract class DeclarationWithParameters<T> : Declaration where T : Declaration
{
    private SyntaxList<T>? _parameters;

    internal DeclarationWithParameters(SyntaxKinds kind, SyntaxToken declareKeywordToken, Identifier name,
        SyntaxNode? parent) :
        base(kind, declareKeywordToken, name, parent)
    {
    }


    /// <summary>
    ///     已定义的参数列表
    /// </summary>
    public ImmutableArray<T> Parameters =>
        _parameters?.ToImmutableArray() ?? ImmutableArray<T>.Empty;


    /// <summary>
    ///     已定义的参数数量
    /// </summary>
    public int ParametersCount => _parameters?.Count ?? 0;


    /// <summary>
    ///     在末尾添加一个参数定义
    /// </summary>
    public void AddParameter(T parameter)
    {
        AddChildMember(ref _parameters, parameter);
    }


    /// <summary>
    ///     获取指定索引的参数定义，如果索引无效，返回null
    /// </summary>
    public T? GetParameterAt(int index)
    {
        if (_parameters != null && index >= 0 && index < ParametersCount)
        {
            return _parameters[index];
        }

        return null;
    }


    /// <summary>
    ///     查找指定参数名的参数定义
    /// </summary>
    /// <param name="parameterName">参数名，宏参数区分大小写，其余情况不区分</param>
    public T? FindParameter(string parameterName)
    {
        return _parameters?.Find(e =>
        {
            if (Parent?.IsNode(SyntaxKinds.MacroDeclaration) == true)
            {
                return parameterName == e.NameIdentifier.Text;
            }

            return parameterName.Equals(e.NameIdentifier.Text, StringComparison.OrdinalIgnoreCase);
        });
    }
}